package com.neuronbit.businessflow.intellij.dialog;

import com.intellij.ide.util.TreeClassChooser;
import com.intellij.ide.util.TreeClassChooserFactory;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.search.GlobalSearchScope;
import org.apache.commons.lang3.StringUtils;
import org.cef.browser.CefBrowser;

/**
 * The type Chooser.
 */
public class Chooser implements Runnable {
    private final Project project;
    private final String returnTypeFilter;
    private final CefBrowser cefBrowser;
    private final String fieldId;
    private final String viewerUrl;

    /**
     * Instantiates a new Chooser.
     *
     * @param project          the project
     * @param returnTypeFilter the return type filter
     * @param cefBrowser       the cef browser
     * @param fieldId          the field id
     * @param viewerUrl        the viewer url
     */
    public Chooser(Project project, String returnTypeFilter, CefBrowser cefBrowser, String fieldId, String viewerUrl) {
        this.project = project;
        this.returnTypeFilter = returnTypeFilter;
        this.cefBrowser = cefBrowser;
        this.fieldId = fieldId;
        this.viewerUrl = viewerUrl;
    }

    @Override
    public void run() {
        TreeClassChooserFactory chooserFactory = TreeClassChooserFactory.getInstance(project);
        GlobalSearchScope searchScope = GlobalSearchScope.allScope(project);
        TreeClassChooser chooser =
                chooserFactory.createNoInnerClassesScopeChooser(
                        "Select Class", searchScope, (psiClass) -> true, null);
        chooser.showDialog();
        final PsiClass selectedPsiClass = chooser.getSelected();
        if (null == selectedPsiClass) {
            return;
        }
        PsiMethodDialog dialog = new PsiMethodDialog(project, selectedPsiClass, returnTypeFilter, GlobalSearchScope.allScope(project));
        dialog.show();
        String selected = dialog.getSelected();
        if (StringUtils.isNotBlank(selected)) {
            cefBrowser.executeJavaScript( // 6
                    """
                            window.AliLowCodeEngine.event.emit('MethodEvent', ['%s','%s']);
                            """.formatted(fieldId, selected),
                    viewerUrl, 0
            );
        }
    }
}
